package com.bungarus.group.auth;

import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.GenericFilterBean;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpHeaderAuthTokenValidationFilter extends GenericFilterBean {
    private final static String X_BUNGARUS_TOKEN = "X-BUNGARUS-TOKEN";

    private final String key;
    private AuthenticationManager authenticationManager;

    public HttpHeaderAuthTokenValidationFilter(AuthenticationManager authenticationManager, final String key) {
        this.key = key;
        this.authenticationManager = authenticationManager;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String token = httpServletRequest.getHeader(X_BUNGARUS_TOKEN);
        if (StringUtils.isEmpty(token)) { //Anonymous
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
        else if (parametersWellFormed(httpServletRequest, httpServletResponse)) {
            String uri = httpServletRequest.getRequestURI();
            Pattern tenantPattern = Pattern.compile("/tenants/(\\d+)/");
            Map<String, Long> IDsFromToken = SessionToken.parseIdentities(token, key);
            if (IDsFromToken.size() == 0) { //Anonymous
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
            else if(authenticationIsRequired(
                    IDsFromToken.get(SessionToken.TENANT_ID) + ":" + IDsFromToken.get(SessionToken.USER_ID))){
                Matcher matcher = tenantPattern.matcher(uri);
                if (!matcher.find()) {
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                    return;
                }
                Long tid = Long.parseLong(matcher.group(1));

                SessionToken authRequest = new SessionToken(-1L, tid, -1L,-1L);
                authRequest.setCredentials(token);

                authRequest = (SessionToken) authenticationManager.authenticate(authRequest);
                if(authRequest.isAuthenticated()) {
                    SecurityContextHolder.getContext().setAuthentication(authRequest);
                    filterChain.doFilter(httpServletRequest, httpServletResponse);
                }
                else {
                    SecurityContextHolder.clearContext();
                    httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
                }
            }
            else {
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }
        }
    }

    private boolean parametersWellFormed(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        return true;
    }

    private boolean authenticationIsRequired(String userId) {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();
        if (existingAuth != null && existingAuth.isAuthenticated()) {
            if (existingAuth instanceof SessionToken) {
                SessionToken sessionToken = (SessionToken)existingAuth;
                if(!existingAuth.getName().equals(userId) || System.currentTimeMillis() - sessionToken.getTimestamp() > sessionToken.getLifetime()) {
                    return true;
                }
                return false;
            }
            else {
                return existingAuth instanceof AnonymousAuthenticationToken;
            }
        }
        else {
            return true;
        }
    }
}
